﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using Akiha.Core;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesGDB;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;




namespace Akiha.Core
{

    //工作空间
    public static class WorkspaceWrapper
    {
        //创建mdb工作空间
        public static IWorkspace CreateMdbWorkspace()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "新建MDB文件";
            saveFileDialog.Filter = "MDB文件(*.mdb)|*.MDB";
            IWorkspace pOutWorkspace = null;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string parentPath = saveFileDialog.FileName.Substring(0, saveFileDialog.FileName.LastIndexOf('\\'));
                string fileName = saveFileDialog.FileName.Substring(saveFileDialog.FileName.LastIndexOf('\\') + 1, saveFileDialog.FileName.Length - saveFileDialog.FileName.LastIndexOf('\\') - 1);
                if (!System.IO.Directory.Exists(parentPath))
                {
                    System.IO.Directory.CreateDirectory(parentPath);
                }
                IWorkspaceFactory pWorkSpaceFactory = new AccessWorkspaceFactoryClass();

                IWorkspaceName pWorkspaceName = pWorkSpaceFactory.Create(parentPath, fileName, null, 0);
                
                

                IName name = (IName)pWorkspaceName;
                pOutWorkspace = (IWorkspace)name.Open();//targetWorkspace
                

            }
            return pOutWorkspace;
        }
        
        //打开mdb工作空间
        public static IWorkspace OpenMdbWorkspace()
        {
            return null;
 
        }

       
       
        /// <summary>
        ///  在工作空间中创建新featureclass，拷贝原featureclass中筛选的字段到其中。
        /// </summary>
        /// <param name="pInFeatureClass">原始Featureclass</param>
        /// <param name="pOutWorkspace">创建featureclass的工作空间</param>
        /// <param name="lstFields">需要保留的字段</param>
        //public static void ExportFeatureToMDB(IFeatureClass pInFeatureClass, IWorkspace pOutWorkspace, List<IField> lstFields)
        //{
        //    IFeatureWorkspace featureWorkspace = pOutWorkspace as IFeatureWorkspace;
        //    //IGeoDataset pGeoDataset = pInFeatureClass as IGeoDataset;//SpatialReference坐标系
        //    //创建数据集
        //    //IFeatureDataset outFeatureDataset = featureWorkspace.CreateFeatureDataset("data", pGeoDataset.SpatialReference);
        //    //创建一个featureClass
        //    String name = "";
        //    if (pInFeatureClass.AliasName.Contains("."))
        //    {
        //        name = pInFeatureClass.AliasName.Split('.')[1];
        //    }
        //    else
        //    {
        //        name = pInFeatureClass.AliasName;
        //    }

        //    IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(name, pInFeatureClass.Fields, null, null, pInFeatureClass.FeatureType, "shape", "");

        //   // IFields pFields = new FieldsClass();

        //    //给FeatureClass赋值
        //   // int featureCount = pInFeatureClass.FeatureCount(null);

        //    IFeature feature;
        //    IWorkspaceEdit workspaceEdit;
        //    IFeatureCursor featureCursor, insertFeatureCursor;
        //    workspaceEdit = pOutWorkspace as IWorkspaceEdit;
        //    //开始编辑
        //    workspaceEdit.StartEditing(true);
        //    workspaceEdit.StartEditOperation();
        //    //导入数据记录
        //    featureCursor = pInFeatureClass.Search(null, true);
        //    insertFeatureCursor = featureClass.Insert(false);

        //    //int count = 0;
        //    while ((feature = featureCursor.NextFeature()) != null)
        //    {
        //        //count++;

        //        insertFeatureCursor.InsertFeature(feature as IFeatureBuffer);
        //        Marshal.ReleaseComObject(feature);          //释放要素
        //        feature = featureCursor.NextFeature();

        //    }


        //    //结束编辑

        //    workspaceEdit.StopEditOperation();
        //    workspaceEdit.StopEditing(true);



        //    Marshal.ReleaseComObject(featureCursor);//释放游标
        //    Marshal.ReleaseComObject(insertFeatureCursor);//释放游标



        //    List<IField> lstCheckFields = CheckFields(featureClass);
        //    //删除没有选中的字段
        //    foreach (IField pField in lstFields)
        //    {
        //        if (!lstFields.Contains(pField))
        //        {
        //            featureClass.DeleteField(pField);
        //        }          
        //    }
            

        //}


        //public static void ExportFeatureToMDB(IFeatureClass pInFeatureClass, IWorkspace pOutWorkspace, List<string> lstFields)
        //{
        //    IFeatureWorkspace featureWorkspace = pOutWorkspace as IFeatureWorkspace;
        //    //IGeoDataset pGeoDataset = pInFeatureClass as IGeoDataset;//SpatialReference坐标系
        //    //创建数据集
        //    //IFeatureDataset outFeatureDataset = featureWorkspace.CreateFeatureDataset("data", pGeoDataset.SpatialReference);
        //    //创建一个featureClass
        //    String name = "";
        //    if (pInFeatureClass.AliasName.Contains("."))
        //    {
        //        name = pInFeatureClass.AliasName.Split('.')[1];
        //    }
        //    else
        //    {
        //        name = pInFeatureClass.AliasName;
        //    }
        //    name = "test";
        //    try
        //    {
        //        IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(name, pInFeatureClass.Fields, null, null,pInFeatureClass.FeatureType, "shape", "");
                
                
        //        // IFields pFields = new FieldsClass();

        //        //给FeatureClass赋值
        //        // int featureCount = pInFeatureClass.FeatureCount(null);

        //        IFeature feature;
        //        IWorkspaceEdit workspaceEdit;
        //        IFeatureCursor featureCursor, insertFeatureCursor;
        //        workspaceEdit = pOutWorkspace as IWorkspaceEdit;
        //        //开始编辑
        //        workspaceEdit.StartEditing(true);
        //        workspaceEdit.StartEditOperation();
        //        //导入数据记录
        //        featureCursor = pInFeatureClass.Search(null, true);
        //        insertFeatureCursor = featureClass.Insert(false);

        //        //int count = 0;
        //        while ((feature = featureCursor.NextFeature()) != null)
        //        {
        //            //count++;

        //            insertFeatureCursor.InsertFeature(feature as IFeatureBuffer);
        //            Marshal.ReleaseComObject(feature);          //释放要素
        //            feature = featureCursor.NextFeature();

        //        }


        //        //结束编辑

        //        workspaceEdit.StopEditOperation();
        //        workspaceEdit.StopEditing(true);


               
        //        Marshal.ReleaseComObject(featureCursor);//释放游标
        //        Marshal.ReleaseComObject(insertFeatureCursor);//释放游标
        //        Marshal.ReleaseComObject(featureClass);       //释放刚刚创建的feacls


        //        List<IField> lstCheckFields = CheckFields(featureClass);
        //        //删除没有选中的字段
        //        ////建库时要将所有字段保存，因为这里只有删除字段的功能
        //        foreach (IField pField in lstCheckFields)
        //        {
        //            if (!lstFields.Contains(pField.Name))
        //            {
        //                featureClass.DeleteField(pField);
        //            }
        //        }
                             

        //    }
        //    catch (Exception ex)
        //    {
                
        //        throw;
        //    }
           

            
            
        //}


        //创建内存要素类
        public static IFeatureClass CreateFeatureLayerInmemeory(string DataSetName, string AliaseName, ISpatialReference SpatialRef, esriGeometryType GeometryType, IFields PropertyFields)
        {
            IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();
            ESRI.ArcGIS.Geodatabase.IWorkspaceName workspaceName = workspaceFactory.Create("", "MyWorkspace", null, 0);
            ESRI.ArcGIS.esriSystem.IName name = (IName)workspaceName;
            ESRI.ArcGIS.Geodatabase.IWorkspace inmemWor = (IWorkspace)name.Open();

            IField oField = new FieldClass();
            IFields oFields = new FieldsClass();
            IFieldsEdit oFieldsEdit = null;
            IFieldEdit oFieldEdit = null;
            IFeatureClass oFeatureClass = null;
           

            try
            {
                oFieldsEdit = oFields as IFieldsEdit;
                oFieldEdit = oField as IFieldEdit;

                for (int i = 0; i < PropertyFields.FieldCount; i++)
                {
                    oFieldsEdit.AddField(PropertyFields.get_Field(i));
                }

                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.AvgNumPoints_2 = 5;
                geometryDefEdit.GeometryType_2 = GeometryType;
                geometryDefEdit.GridCount_2 = 1;
                geometryDefEdit.HasM_2 = false;
                geometryDefEdit.HasZ_2 = false;
                geometryDefEdit.SpatialReference_2 = SpatialRef;

                oFieldEdit.Name_2 = "SHAPE";
                oFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                oFieldEdit.GeometryDef_2 = geometryDef;
                oFieldEdit.IsNullable_2 = true;
                oFieldEdit.Required_2 = true;
                oFieldsEdit.AddField(oField);

                oFeatureClass = (inmemWor as IFeatureWorkspace).CreateFeatureClass(DataSetName, oFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
                (oFeatureClass as IDataset).BrowseName = DataSetName;

               
            }
            catch
            {
            }
            finally
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oField);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFields);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldsEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(name);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFactory);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceName);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFeatureClass);
                }
                catch { }

                GC.Collect();
            }
            return oFeatureClass;
        }






    }

}
